package com.atguigu.gmall.realtime.util;

import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author lzc
 * @Date 2023/4/22 15:01
 */
public class AtguiguUtil {
    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static Set<String> ikSplit(String s) {
        HashSet<String> set = new HashSet<>();
        // string => reader
        StringReader reader = new StringReader(s);  // 内存流
        IKSegmenter segmenter = new IKSegmenter(reader, true);  // 非智能模式: max_word
        
        Lexeme next = null;
        try {
            next = segmenter.next(); // 截取第一个词
            while(next != null){
                String kw = next.getLexemeText(); // 取出具体的字符串
                set.add(kw);
                next = segmenter.next(); // 截取下一个
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return set;
    }
    
    public static String tsToDate(long ts) {
       // return new SimpleDateFormat("yyyy-MM-dd").format(ts);  // 有线程安全问题
        Date dt = new Date(ts);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(dt.toInstant(), ZoneId.systemDefault());
        return dateFormatter.format(localDateTime);
    }
    
    public static String tsToDateTime(long ts) {
        Date dt = new Date(ts);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(dt.toInstant(), ZoneId.systemDefault());
        return dateTimeFormatter.format(localDateTime);
    }
    // yyyy-MM-dd -> ts
    public static Long dateToTs(String date) {
        return dateTimeToTs(date + " 00:00:00");
    }
    
    // yyyy-MM-dd HH:mm:ss ->ts
    public static Long dateTimeToTs(String dateTime) {
        LocalDateTime localDateTime = null;
        
        localDateTime = LocalDateTime.parse(dateTime, dateTimeFormatter);
    
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }
    
    public static void main(String[] args) {
        System.out.println(dateTimeToTs("1970-01-01 08:01:00"));
    }
    
}
